<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <script src="/vue/vue.js"></script>
    <script src="/axios/axios.min.js"></script>
    <script src="/qs/qs.min.js"></script>
    <script src="/elementui/index.js"></script>
    <link rel="stylesheet" href="/elementui/index.css">
    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
    <div id="app">
        <el-row>
            <el-button type="primary" @click="showTreeDialog">给用户编辑角色</el-button>
            <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        </el-row>
        <hr style="height: 0px;color: gainsboro">
        <template>
            <el-table
                    ref="userTable"
                    :data="tableData"
                    height="449"
                    border
                    stripe
                    tooltip-effect="dark"
                    style="width: 100%"
                    :header-cell-style="{background:'#B3C0D1',color:'#ffffff'}"
                    @selection-change="handleSelectionChange"
                    @select-all="selectAll"
                    @select="select"
                    @current-change="changeCurrentUser">
                <el-table-column
                        fixed
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="id"
                        label="编号"
                        width="120">
                </el-table-column>
                <el-table-column
                        prop="userName"
                        label="用户名"
                        width="200">
                </el-table-column>
                <el-table-column
                        prop="passWord"
                        label="密码"
                        width="700">
                </el-table-column>
                <el-table-column
                        prop="realName"
                        label="真实姓名"
                        width="200">
                </el-table-column>
                <el-table-column
                        prop="salt"
                        label="密码加盐"
                        width="150">
                </el-table-column>
                <el-table-column
                        prop="userTel"
                        label="电话"
                        width="200">
                </el-table-column>
                <el-table-column
                        label="头像"
                        width="100">
                    <template slot-scope="scope">
                        <el-image
                                style="width: 50px; height: 50px"
                                :src="'http://121.5.226.17/images/'+scope.row.userImage"
                                :preview-src-list="['http://121.5.226.17/images/'+scope.row.userImage]">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="200">
                    <template slot-scope="scope">
                        <el-button
                                size="normal"
                                @click="editUser(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="normal"
                                type="danger"
                                @click="deleteUser(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @prev-click="prev"
                    @next-click="next"
                    @current-change="currentChange"
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :current-page="current"
                    :page-size="pageSize">
            </el-pagination>
        </template>

        <!--        增改-->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                @close="closeDialog"
                :close-on-click-modal="false"
                width="60%">
            <el-form :model="user">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入用户名"
                            v-model="user.userName"
                            autocomplete="off"
                            clearable
                            maxlength="10"
                            show-word-limit
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
                <el-form-item label="真实姓名" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入真实姓名"
                            v-model="user.realName"
                            autocomplete="off"
                            clearable
                            maxlength="20"
                            show-word-limit
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
                <el-upload
                        style="position: absolute;right: 100px;top: 85px;"
                        class="avatar-uploader"
                        action="/up/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="user.userImage" :src="'http://121.5.226.17/images/'+user.userImage" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入密码"
                            v-model="user.passWord"
                            autocomplete="off"
                            clearable
                            maxlength="10"
                            show-word-limit
                            show-password
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
                <el-form-item label="确定密码" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请再次输入密码"
                            clearable
                            v-model="user.rePassword"
                            autocomplete="off"
                            maxlength="10"
                            show-word-limit
                            show-password
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
                <el-form-item label="电话" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入电话号码"
                            clearable
                            v-model="user.userTel"
                            autocomplete="off"
                            maxlength="20"
                            show-word-limit
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser" :style="{display: addBtnShow}">添加</el-button>
                <el-button type="primary" @click="modifyUser" :style="{display: modifyBtnShow}">修改</el-button>
            </div>
        </el-dialog>

        <!--        树形对话框-->
        <el-dialog
                title="给用户编辑角色"
                :visible.sync="dialogTreeVisible"
                width="30%"
                :close-on-click-modal="false"
                @close="closeTreeDialog">
            <el-tree
                    :data="roles"
                    show-checkbox
                    node-key="id"
                    ref="tree"
                    @check="checkClick"
                    highlight-current
                    :default-checked-keys="idArr"
                    :props="defaultProps">
            </el-tree>
        </el-dialog>
</div>
</body>
<script>
    var Main = {
        data() {
            return {
                tableData: [],  //表格数据
                current:1,  //当前行
                total:1,    //总行数
                pageSize:10,    //页码
                pages:1,    //页数
                dialogFormVisible: false,
                dialogTitle: '添加用户信息',
                addBtnShow:'',
                modifyBtnShow:'none',
                user: {
                    id: '',
                    userName: '',
                    passWord: '',
                    rePassword: '',
                    realName:'',
                    salt:'',
                    userTel:'',
                    userImage:'',
                },
                formLabelWidth: '120px',
                currentUser:null,   //当前选中角色
                multipleSelection: [],
                dialogTreeVisible:false, //显示权限树对话框
                defaultProps: { //修改树属性的名称
                    children: '',
                    label: 'roleName'
                },
                roles:[],   //角色数据
                idArr: [],    //默认当前选中的角色所有的权限
            }
        },
        methods: {
            //分页上一页
            prev(current){
                this.getPage(current);
            },
            //分页下一页
            next(current){
                this.getPage(current);
            },
            //分页当前页点击
            currentChange(current){
                this.getPage(current);
            },
            //点击选择用户
            //加载数据
            getPage(current){
                axios.get("/users?current="+current).then(value => {
                    if (value.data.state==1){
                        console.log(value)
                        this.tableData = value.data.data.records;
                        this.current = value.data.data.current;
                        this.total = value.data.data.total;
                        this.pageSize = value.data.data.size;
                        this.pages = value.data.data.pages;
                    }
                });
            },
            //修改用户
            editUser(index,row){
                //显示对话框
                this.dialogFormVisible = true;
                //修改对话框标题
                this.dialogTitle = '修改用户信息'
                //显示修改按钮，隐藏添加按钮
                this.addBtnShow = 'none';
                this.modifyBtnShow = '';
                //回显选中的用户信息
                this.user.id = row.id;
                this.user.userName = row.userName;
                this.user.realName = row.realName;
                this.user.salt = row.salt;
                this.user.userTel = row.userTel;
                this.user.userImage = row.userImage;
            },
            //修改用户
            modifyUser(){
                axios.put("/user",this.user).then(value => {
                    if (value.data.state==1){
                        //弹出框提示
                        this.sendMessage("修改成功","success");
                        //关闭弹出框
                        this.dialogFormVisible = false;
                    }else {
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //删除用户
            deleteUser(index,row){
                if (confirm("确定删除吗?")){
                    axios.delete("/user/"+row.id).then(value => {
                        if (value.data.state==1){
                            //弹出框提示添加成功
                            this.sendMessage("删除成功","success");
                            //刷新页面
                            //判断是否为最后一页
                            if (this.current == this.pages && this.current > 1){
                                //判断是否为最后一条数据
                                if (this.total%this.pageSize==1){
                                    this.current -= 1;
                                }
                            }
                            this.getPage(this.current);
                        }
                    });
                }else {
                    this.sendMessage("出错啦","error");
                }
            },
            //添加用户
            addUser(){
                console.log(this.user);
                axios.post("/user",this.user).then(value => {
                    if (value.data.state==1){
                        //弹出框提示添加成功
                        this.sendMessage("添加成功","success");
                        //关闭弹出框
                        this.dialogFormVisible = false;
                    }else {
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //打开用户的对话框
            showAddDialog(){
                this.dialogFormVisible = true;
                this.dialogTitle = '添加用户';
                this.addBtnShow = '';
                this.modifyBtnShow = 'none';
            },
            //关闭对话框后清除数据刷新页面
            closeDialog(){
                this.user.userName = '';
                this.user.passWord = '';
                this.user.rePassword = '';
                this.user.realName = '';
                this.user.salt = '';
                this.user.userTel = '';
                this.user.userImage = '';
                this.getPage(this.current);
            },
            //上传图片成功后
            handleAvatarSuccess(res, file) {
                this.user.userImage = res.message;
            },
            //上传图片前检验
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //当前列改变时
            changeCurrentUser(row){
                this.currentUser = row;
                //取消所有的选择效果
                this.$refs.userTable.clearSelection();
                //选中当前的行
                this.$refs.userTable.toggleRowSelection(row);
            },
            //全选按钮
            selectAll(){
                this.$refs.userTable.clearSelection();
            },
            //选择当前checkbox时
            select(selection,row){
                this.changeCurrentUser(row);
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //根据用户获得角色
            getIdArr(id){
                //id数组
                let idArr = [];
                //通过角色id获得权限
                axios.get("/role",{params:{userId:id}}).then(value => {
                    //返回的权限
                    let roles = value.data.data;
                    for (let role of roles) {
                        idArr.push(role.id);
                    }
                    //赋给默认选中
                    this.idArr = idArr;
                })
            },
            //获得所有角色
            getRole(){
                axios.get("/getRoles").then(value => {
                    if (value.data.state==1){
                        this.roles = value.data.data;
                    }
                });
            },
            //显示授权对话框
            showTreeDialog(){
                if (this.currentUser){
                    //获取当前选中用户的id
                    let id = this.currentUser.id;
                    this.getIdArr(id);
                    this.dialogTreeVisible = true;
                }else {
                    this.sendMessage("请选择用户！","warning");
                }
            },
            //复选框选中
            checkClick(data,objArr){

                //1、判断是选中还是取消选中
                let flat = false;   //true为选中（添加），false为取消（删除）
                //遍历已选中的数组，判断当前选择节点是否存在
                for (let obj of objArr.checkedNodes) {
                    if (obj == data){
                        flat = true;
                        break;
                    }
                }

                if (flat){
                    // 添加：添加当前选中节点
                    this.addRole(data.id);
                }else {
                    // 删除：删除当前取消节点
                    this.deleteRole(data.id);
                }

            },
            //添加权限
            addRole(id){
                let param = new URLSearchParams();
                param.append("roleId",id);
                param.append("userId",this.currentUser.id);
                axios.post("/userRole",param).then(value => {
                    if (value.data.state==1){
                        this.sendMessage("修改角色成功","success");
                    }else{
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //删除权限
            deleteRole(id){
                let param = new URLSearchParams();
                param.append("roleId",id);
                param.append("userId",this.currentUser.id);
                axios.delete("/userRole",{params:param}).then(value => {
                    if (value.data.state==1){
                        this.sendMessage("修改角色成功","success");
                    }else{
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //关闭对话框
            closeTreeDialog(){
                //清除所有选中节点
                this.$refs.tree.setCheckedKeys([]);
                //清除所有展开的节点
                this.$refs.tree.store._getAllNodes().forEach(node => {
                    node.expanded = false;
                })
            },
            //提示信息
            sendMessage(msg,type){
                this.$message({
                    showClose: true,
                    message: msg,
                    type: type
                });
            }
        },
        mounted(){
            //加载数据
            this.getPage(1);
            this.getRole();
        }
    }
    var Ctor = Vue.extend(Main)
    new Ctor().$mount('#app')
</script>
</html>